package com.xinongbest.config;

import com.xinongbest.pojo.Configuration;
import com.xinongbest.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream input) throws DocumentException {
        Document document = new SAXReader().read(input);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectNodes = rootElement.selectNodes("//select");
        MappedStatement mappedStatement;
        for (Element selectNode : selectNodes) {
            mappedStatement = new MappedStatement();
            String id = selectNode.attributeValue("id");
            mappedStatement.setId(id);
            mappedStatement.setParameterType(selectNode.attributeValue("parameterType"));
            mappedStatement.setResultType(selectNode.attributeValue("resultType"));
            mappedStatement.setSql(selectNode.getTextTrim());
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
